<?php

namespace app\api\controller\v2;

use app\admin\model\User;
use app\api\services\WXQrcode;
use app\common\controller\Frontend;
use ba\Random;
use think\facade\Db;
use think\facade\Log;

class ShareWxQrcode extends Frontend
{

    protected array $noNeedLogin = ['wx_xml'];

    public function initialize (): void
    {
        parent::initialize();
    }


    /**
     * 获取普通用户二维码（临时 30天）
     * @return void
     */
    public function getUserShareQrcode (): void
    {
        $userInfo = User::where('id', $this->auth->id)->find();
        #生成唯一id
        if (empty($userInfo->share_uuid)) {
            $userInfo->share_uuid = Random::uuid();
            $userInfo->save();
        }

        $codeInfo = Db::name('user_share_qrcode')->where('user_id', $this->auth->id)->where('type', 0)->where('expired_time', '>', time())->find();
        if (empty($codeInfo) || $codeInfo['expired_time'] < time()) {
            #生成二维码
            $path = (new WXQrcode)->shareTemporaryQrCode($userInfo->share_uuid);
            if (empty($path)) {
                $this->error('生成二维码失败');
            }
            #保存二维码
            Db::name('user_share_qrcode')->insert([
                'user_id'      => $this->auth->id,
                'type'         => 0,
                'qrcode'       => $path . '/' . $userInfo->share_uuid . '.png',
                'create_time'  => date('Y-m-d H:i:s', time()),
                'expired_time' => time() + 2592000
            ]);
        }
        $url = $codeInfo['qrcode'] ?? $path . '/' . $userInfo->share_uuid . '.png';
        $this->success('获取成功', [
            'qrcode'  => IMAGE_URL . $url,
            'uuid'    => $userInfo->share_uuid,
            'user_id' => $this->auth->id
        ]);
    }


    /**
     * 获取推广员永久二维码
     * @return void
     */
    public function getExtendShareQrcode (): void
    {
        $userInfo = User::where('id', $this->auth->id)->find();
        if ($userInfo->is_extend != 1) {
            $this->error('您不是推广员');
        }
        if ($userInfo->extend_status != 1) {
            $this->error('您的推广员身份已被禁用');
        }
        #生成唯一id
        if (empty($userInfo->extend_share_uuid)) {
            $userInfo->extend_share_uuid = Random::uuid();
            $userInfo->save();
        }

        $codeInfo = Db::name('user_share_qrcode')->where('user_id', $this->auth->id)->where('type', 1)->find();
        if (empty($codeInfo)) {
            #生成二维码
            $path = (new WXQrcode)->sharePermanentQrCode($userInfo->extend_share_uuid);
            if (empty($path)) {
                $this->error('生成二维码失败');
            }
            #保存二维码
            Db::name('user_share_qrcode')->insert([
                'user_id'      => $this->auth->id,
                'type'         => 1,
                'qrcode'       => $path . '/' . $userInfo->extend_share_uuid . '.png',
                'create_time'  => date('Y-m-d H:i:s', time()),
                'expired_time' => 0
            ]);
        }
        $url = $codeInfo['qrcode'] ?? $path . '/' . $userInfo->extend_share_uuid . '.png';
        $this->success('获取成功', [
            'qrcode'  => IMAGE_URL . $url,
            'uuid'    => $userInfo->extend_share_uuid,
            'user_id' => $this->auth->id
        ]);
    }


    public function wx_xml ()
    {

        Log::info('微信xml' . json_encode($_GET));
        $echostr = $_GET["echostr"] ?? null;
        if (!empty($echostr) && $this->checkSignature()) return $echostr;

        $xml = file_get_contents('php://input');
        Log::info('微信xml-input' . $xml);

        $xml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $data = json_decode(json_encode($xml), true);
        Log::info('微信xml-json' . json_encode($data));

        #扫码事件event text 消息
        if ($data['MsgType'] != 'event') {
            return 'SUCCESS';
        }


        $EventKey = empty($data['EventKey']) ? $data['EventKey'] : ""; //自定义参数
        $FromUserName = $data['FromUserName']; //用户open_id

        if ($data['Event'] == 'subscribe') {
            (new WXQrcode)->send($FromUserName);
            return 'SUCCESS';
        }
        #注册用户
        $this->signIn($EventKey, $FromUserName);
        return 'SUCCESS';
    }


    /**
     * 注册用户
     * 微信公众号授权登录
     */
    private function signIn ($uuid, $openid)
    {
        $user = new User;
        $find = $user
            ->where(['open_id' => $openid])
            ->find();
        if (empty($find)) {
            // 没有则注册
            $user->username = Random::uuid();
            $user->nickname = '用户' . Random::build(8);
            $user->avatar = '';
            $user->status = 'enable';
            $user->open_id = $openid;
            $user->save();
            #送优惠券
            event('couponGifts', [
                'user_id' => $user->id,
                'gifts'   => 'register'
            ]);

            $parent_user_id = 0;
            $type = 0;
            if (!empty($uuid)) {
                #绑定用户 普通用户
                $normalUser = User::where('share_uuid', $uuid)->find();
                if (!empty($normalUser)) {
                    $parent_user_id = $normalUser->id;
                }
                $extendUser = User::where('extend_share_uuid', $uuid)->find();
                if (!empty($extendUser)) {
                    $parent_user_id = $extendUser->id;
                    $type = 1;
                }

                Db::name('user_level')->insert([
                    'user_id'        => $user->id,
                    'parent_user_id' => $parent_user_id,
                    'type'           => $type,
                    'create_time'    => date('Y-m-d H:i:s', time())
                ]);
            }

        }
        return true;
    }

    private function checkSignature ()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = 'ba1f2511fc30423bdbb183fe33f3dd0';
        $tmpArr = array ($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }


}

